package com.koicarp.university.graduate.service.qiniuyun;

import com.koicarp.university.graudate.common.constant.BaseConstant;
import com.koicarp.university.graudate.common.utils.UniversityResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @auther liutao
 * @Date 2020-12-04 14:29:36
 */
@Slf4j
@Service("fileService")
public class FileServiceImpl {

    @Value("${my.qiniu.image.namespace}")
    private String imageNameSpace;

    public UniversityResponse imageLoad(MultipartFile file) {
        UniversityResponse response = new UniversityResponse();
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage == null){
                // 文件非图片
               response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
               response.message("文件上传为空");
                return response;
            }
//            fileVO.setWidth(bufferedImage.getWidth());
//            fileVO.setHeight(bufferedImage.getHeight());
            bufferedImage = null;
            String url = QiniuUpload.updateFile(file, imageNameSpace, QiniuUpload.getNewFileName(file.getOriginalFilename()));
            response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);
            response.data(url);
        } catch (IOException e) {
            log.error(e.getMessage());
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED+":" + file.getName());
        }
        return response;
    }
}
